package my.mark.mybaibaoxiang.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * spring context utils.
 * @Description: String工具类，非Spring容器管理的类获取spring容器里的对象。
 * @Author wxming
 * @Date 2019年8月11日 下午7:13:58
 */
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(String beanId) {
        assertContext();
        return (T) context.getBean(beanId);
    }

    public static <T> T getBean(String beanId, Class<T> clazz) {
        assertContext();
        return context.getBean(beanId, clazz);
    }

    public static void assertContext() {
        if (Objects.isNull(context)) {
            throw new NullPointerException();
        }
    }

    public static <T> T getBean(Class<T> type) {
        assertContext();
        return context.getBean(type);
    }

    public static <T> List<T> getBeansWithAnnotation(Class<? extends Annotation> var1) {
        assertContext();
        return new ArrayList<T>((Collection<? extends T>) context.getBeansWithAnnotation(var1).values());
    }


    public static String[] getBeanNamesForType(Class<?> clazz) {
        assertContext();
        return context.getBeanNamesForType(clazz);
    }

}
